﻿using System.Diagnostics;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;

namespace BlogsAPI.Shorteners
{
    using System;
    using System.IO;
    using System.Net;
    using Abstract;
    using System.Web;

    /// <summary>
    /// Google URL Shortener at goo.gl is a service that takes long URLs and squeezes them 
    /// into fewer characters to make a link that is easier to share, tweet, or email to friends.  
    /// </summary>
    /// <remarks>
    /// There is only 1 function:
    /// https://developers.google.com/url-shortener/v1/getting_started#shorten
    /// </remarks>
    [SingleShortener(Link = "https://goo.gl/")]
    public class Googl : Shortener
    {
        /// <summary>
        /// Преобразование одного типа данных в другой
        /// </summary>
        /// <param name="sInData">входные данные</param>
        /// <param name="sInType">входной тип</param>
        /// <param name="sOutType">выходной тип</param>
        /// <returns>Данные выходного типа</returns>
        /// <remarks>The fuction has bad code style</remarks>
        public override String ConvertDataTo(string sInData, ItemType sInType, ItemType sOutType)
        {
            if(sInType == ItemType.Clicks) return null;//cant be!
            if(sOutType == ItemType.User) return null;//cant be!
            if (sInType == sOutType) return sInData;

            if (sInType != ItemType.FullUrl || sOutType != ItemType.ShortUrl)
            {
                 //банальное преобразование
                 return base.ConvertDataTo(sInData, sInType, sOutType);
            }
            //
            try
            {
                HttpWebRequest request = MakeRequest("https://www.googleapis.com/urlshortener/v1/url");
                    //prepare web request
                request.Method = "POST";
                request.ContentType = "application/json";
                request.AllowAutoRedirect = false;
                string sQueryString = "{\"longUrl\": \"" + sInData + "\"}";
                //странности с кодировкой =(
                byte[] byteArr = System.Text.Encoding.UTF8.GetBytes(sQueryString);
                request.ContentLength = byteArr.Length;
                request.GetRequestStream().Write(byteArr, 0, byteArr.Length);

                HttpWebResponse resp = (HttpWebResponse) request.GetResponse();
                StreamReader responseStream = new StreamReader(resp.GetResponseStream()); //prepare responese holder
                String response = responseStream.ReadToEnd(); //fill up response
                responseStream.Close(); //Close stream
                JObject ret = JObject.Parse(response);
                return ret["id"].Value<string>();
            }catch(Exception e1)
            {
                Debug.Write(e1);
            }
            return null;
        }
    }
}
